package org.webrtc.yl.WebSocket;

import android.util.Log;

import org.webrtc.yl.WebSocket.Listener.ClientWebSocketListener;
import org.webrtc.yl.WebSocket.Listener.ServiceWebSocketListener;

import org.java_websocket.WebSocket;

import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;

public class AndroidWebsocketManager implements ServiceWebSocketListener, ClientWebSocketListener {
    private static final String TAG = "WebsocketManager";

    private final TCPChannelEvents eventListener;

    private AndroidWebSocketServer webSocketServer;
    private AndroidWebSocketClient webSocketClient;

    //////////////////////////////////////Server start///////////////////////////
    @Override
    public void onClientOpen(WebSocket conn, String address) {

    }

    @Override
    public void onClientClose(WebSocket conn, int code, String reason, boolean remote) {

    }

    @Override
    public void onClientMessage(WebSocket conn, String message) {

    }

    @Override
    public void onClientError(WebSocket conn, Exception ex) {

    }

    @Override
    public void onServerStart() {

    }

    @Override
    public void onMessage(String message) {

    }
    //////////////////////////////////////Server end///////////////////////////

    //////////////////////////////////////client start///////////////////////////
    @Override
    public void onOpen(String message) {

    }

    @Override
    public void onClose(String message) {

    }

    @Override
    public void onError(String message) {

    }
    //////////////////////////////////////client end///////////////////////////

    public interface TCPChannelEvents {
        void onTCPConnected(boolean server);

        void onTCPMessage(String message);

        void onTCPError(String description);

        void onTCPClose();
    }

    public AndroidWebsocketManager(ExecutorService executor, TCPChannelEvents eventListener, String ip, int port) {
        this.eventListener = eventListener;

        InetAddress address;
        try {
            address = InetAddress.getByName(ip);
        } catch (UnknownHostException e) {
            reportError("Invalid IP address.");
            return;
        }

        if (address.isAnyLocalAddress()) {
            webSocketServer = new AndroidWebSocketServer(port, this);
        } else {
            //URI uri = new URI("ws://10.10.10.104:9007");
            try {
                URI uri = new URI("ws://" + address + ":" + port);
                webSocketClient = new AndroidWebSocketClient(uri, this);
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }

        }
    }

    private void reportError(final String message) {
        Log.e(TAG, "TCP Error: " + message);
        if (eventListener != null) {
            eventListener.onTCPError(message);
        }
    }
}
